package core
{
	import com.rafaelrinaldi.sound.SoundManager;
	
	import flash.utils.getTimer;
	
	import interfaces.IState;
	
	import objects.Background;
	
	import starling.display.Sprite;
	import starling.events.Event;
	
	import states.GameOver;
	import states.Menu;
	import states.Play;
	
	public class Game extends Sprite
	{
		/**
		 * Constants representing the game states.  This will be used in the state machine.
		 * */
		public static const MENU_STATE:int = 0;
		public static const PLAY_STATE:int = 1;
		public static const GAME_OVER_STATE:int = 2;
		public static const SOUND_MANAGER:SoundManager = new SoundManager("sm");
		
		private var _currentState:IState;
		private var _background:Background;
		
		/**
		 * Game loop timers.
		 * */
		private var _currentTime:Number = 0;
		private var _lastTime:Number = 0;
		private var _delta:Number = 0;
		private var _deltaSmall:Number = 0;
		
		public function Game()
		{
			Assets.init();
			
			this.addEventListener(Event.ADDED_TO_STAGE, init);
			
			SOUND_MANAGER.add(Assets.PLAY_PLAYER_SHOOT, new Assets.SoundPlayerShoot());
			SOUND_MANAGER.add(Assets.PLAY_ENEMY_EXPLODE, new Assets.SoundEnemyExplode());
			SOUND_MANAGER.add(Assets.PLAY_BACKGROUND_MUSIC, new Assets.SoundBackgroundMusic());
			
			super();
		}
		
		public function switchState(state:int):void
		{
			/**
			 * Check if the current state isn't null, that means there is a state Class already running.  Destroy
			 * that state and set to null.
			 * */
			if (_currentState != null)
			{
				destroyCurrentState();
			}
			
			/**
			 * Switching states.
			 * */
			switch (state)
			{
				case MENU_STATE:
					_currentState = new Menu(this);
					break;
				case PLAY_STATE:
					_currentState = new Play(this);
					break;
				case GAME_OVER_STATE:
					_currentState = new GameOver(this);
					stopBackgroundMusic();
					break;
			}
			
			this.addChild(_currentState as Sprite);
		}
		
		private function stopBackgroundMusic():void
		{
			Game.SOUND_MANAGER.item(Assets.PLAY_BACKGROUND_MUSIC).stop();
		}
		
		private function init(e:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, init);
			
			_background = new Background();
			this.addChild(_background);
			
			switchState(MENU_STATE);
			
			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		private function update(e:Event):void
		{
			_currentTime = getTimer();
			_delta = _currentTime - _lastTime;
			_deltaSmall = _delta * .001;
			
			_currentState.update(_deltaSmall);
			
			_background.update(_deltaSmall);
			
			_lastTime = _currentTime;
		}
		
		private function destroyCurrentState():void
		{
			_currentState.destroy();
			this.removeChild(_currentState as Sprite);
			(_currentState as Sprite).dispose();
			_currentState = null;
		}
	}
}



































